package keeto.com.vn.classified.ui;

import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.utils.StatusMessageUtil;
import keeto.com.vn.classified.utils.Utils;
import keeto.com.vn.classified.utils.ValidatorString;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class UserProfileActivity extends Activity implements OnClickListener {
	static final int DATE_DIALOG_ID = 0;
	static final int DATE_DIALOG_HIGH_SCHOOL = 1;
	static final int DATE_DIALOG_COLLEGE = 2;
	private EditText etDisplayName;
	private RadioButton rbMale;
	private RadioButton rbFemale;
	private Spinner spArea;
	private EditText etEmail;
	private EditText etMobile;
	private Button btnSubmit;
	private TextView tvTitle;
	private Vector<Area> vtAreas = null;
	private ArrayAdapter<String> spAreaAdapter = null;
	private ProgressDialog mProgressDialog = null;
	private ViewHandler mHandler = new ViewHandler();
	private UserProfileListener mListener = new UserProfileListener();
	private Button btnChangePass;
	private static InUIThreadHandler mReturnCodeHandler = null;
	private String mArea = null;
	private String[] listArea;
	private ImageButton btnTitleBack;
	private BuiltinService service;
	private BuiltinServiceManager builtinServiceManager;
	private String displayName;
	private String areaID;
	private String mobile;
	private ImageView imgSearch;
	private String gender ="";
	private String Email;
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";


	public static void actionLaunch(Context context) {
		Intent i = new Intent(context, UserProfileActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mReturnCodeHandler = new InUIThreadHandler();
		setContentView(R.layout.user_profile_view);
		builtinServiceManager = BuiltinServiceManager.getInstance(this);
		service = builtinServiceManager.getBuitinService();
		initLayout();

	}

	/**
	 * init Layout and add data to ui
	 */
	private void initLayout() {
		imgSearch=(ImageView)findViewById(R.id.btn_sub_title_search_home);
		imgSearch.setVisibility(View.GONE);
		tvTitle = (TextView) findViewById(R.id.tv_sub_title_text);
		spArea = (Spinner) findViewById(R.id.sp_area);
		etDisplayName = (EditText) findViewById(R.id.et_display_name);
		etEmail = (EditText) findViewById(R.id.edt_email_update);
		etMobile = (EditText) findViewById(R.id.edt_phone_number);
		btnSubmit = (Button) findViewById(R.id.btn_submite);
		btnChangePass = (Button) findViewById(R.id.btn_change_pass);
		btnTitleBack=(ImageButton)findViewById(R.id.btn_sub_title_back);
		btnTitleBack.setOnClickListener(this);
		rbMale = (RadioButton) this.findViewById(R.id.rb_male);
		rbFemale = (RadioButton) this.findViewById(R.id.rb_female);
		tvTitle.setText(this.getResources().getString(R.string.menu_bar_info));
		mArea = service.getAreaID();
		vtAreas = IAManager.getInstance(this).getAllArea();
		listArea = Utils.getTextofArea(vtAreas);
		spAreaAdapter = new ArrayAdapter<String>(this, 
				android.R.layout.simple_spinner_item, listArea);
		spAreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spArea.setAdapter(spAreaAdapter);

		for(int i =0; i< spAreaAdapter.getCount() ;i++){
			if (vtAreas.elementAt(i).getRemoteId().equals(mArea)){
				spArea.setSelection(i);
				break;
			}
		}

		btnChangePass.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		mProgressDialog = new ProgressDialog(UserProfileActivity.this);
		mHandler.refreshUI();
	}
	class ViewHandler {

		public void refreshUI() {
			runOnUiThread(new Runnable() {


				@Override
				public void run() {
					String displayName = service.getDisplayName();
					String phone = service.getUserPhone();
					String emailAddress = service.getUserEmail();
					int sex = service.getSex();

					etDisplayName.setText(displayName == null ? ""
							: displayName);

					if (sex == 1){
						rbMale.setChecked(true);
						rbFemale.setChecked(false);
					}else{
						rbFemale.setChecked(true);
						rbMale.setChecked(false);
					}

					if (TextUtils.isEmpty(emailAddress)){
						etEmail.setEnabled(true);
						etEmail.setHint(R.string.tv_add_email);
					}else{
						etEmail.setEnabled(false);

					}
					etEmail.setText(emailAddress == null ? ""
							: emailAddress);

					etMobile.setText(phone == null ? "" : phone);
					if(phone.equals("")){
						etMobile.setHint(R.string.txt_add_phone);
						etMobile.setHintTextColor(Color.GRAY);
					} 
				}

			});
		}

		public void showMessageToast(final String message) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Toast.makeText(UserProfileActivity.this, message,
							Toast.LENGTH_SHORT).show();
				}

			});
		}

		public void showProgressDialog(final String message) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					mProgressDialog.setMessage(message);
					mProgressDialog.show();
				}

			});
		}

		public void dismissProgressDialog() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mProgressDialog.dismiss();
				}
			});
		}

		public void showNetworkErrorToast() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					String message = getString(R.string.msg_connection_timeout);
					StatusMessageUtil.getInstance(UserProfileActivity.this)
					.showCustomWarningToast(UserProfileActivity.this,
							message, 0);
				}

			});
		}
	}

	class UserProfileListener extends ClassifiedListener {
		@Override
		public void finishUpdateUserProfile(int returnCode) {
			super.finishUpdateUserProfile(returnCode);
			mHandler.dismissProgressDialog();
			if (returnCode == IProtocol.STATUS_CODE_OK_200) {
				if (!TextUtils.isEmpty(displayName))
					service.setDisplayName(displayName);
				if (gender.equals("Nam")){
					service.setSex(1);
				}else{
					service.setSex(0);
				}
				if (!TextUtils.isEmpty(areaID))
					service.setAreaID(areaID);
				if (!TextUtils.isEmpty(mobile))
					service.setUserPhone(mobile);
				if (!TextUtils.isEmpty(mobile))
					service.setUserPhone(mobile);
				if (!TextUtils.isEmpty(Email))
					service.setUserEmail(Email);

				builtinServiceManager.saveBuitinService(service);

				mHandler.showMessageToast(StatusMessageUtil.getInstance(
						UserProfileActivity.this).getStatusMessageByStatus(
								returnCode));
			} else {
				mReturnCodeHandler.takeActionByReturnCode(
						UserProfileActivity.this, returnCode, false);
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_change_pass:
			ChangePassActivity.actionLaunch(this);
			break;
		case R.id.btn_submite:
			validateInfoAndUpdate();
			break;
		case R.id.btn_sub_title_back:
			finish();
			break;
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		ClassifiedCore.getInstance(getApplication()).removeListener(mListener);
	}

	@Override
	protected void onResume() {
		super.onResume();
		ClassifiedCore.getInstance(getApplication()).addListener(mListener);
	}

	public void validateInfoAndUpdate() {
		if (TextUtils.isEmpty(etDisplayName.getText().toString())) {
			setErrorMsg(getResources().getString(R.string.user_profile_enter_first_name), etDisplayName);
			etDisplayName.requestFocus();
			return;
		}
		if (!TextUtils.isEmpty(etMobile.getText().toString())) {
			String phone = etMobile.getText().toString();
			Pattern p2 = Pattern.compile("^\\d{5,16}$");
			Matcher matcher2 = p2.matcher(phone);
			if (!matcher2.matches()) {
				setErrorMsg(getResources().getString(R.string.user_profile_enter_correct_mobile), etMobile);
				etMobile.requestFocus();
				return;
			}
		}
		displayName = etDisplayName.getText().toString();
		gender = rbMale.isChecked() ? rbMale.getText().toString() : rbFemale.getText().toString();
		for(int i =0; i< spAreaAdapter.getCount() ;i++){
			if (vtAreas.elementAt(i).getName().equals(spArea.getSelectedItem())){
				areaID = vtAreas.elementAt(i).getRemoteId();
				break;
			}
		}
		Email = etEmail.getText().toString();
		ValidatorString strEmailformat = new ValidatorString(EMAIL_PATTERN);

		if (!strEmailformat.validate(Email)){
			setErrorMsg(getResources().getString(R.string.ia_public_error), etEmail);
			etEmail.requestFocus();
			return;
		}
		if (Email.equals(service.getUserName())){
			Email = "";
		}
		mobile = etMobile.getText().toString();
		ClassifiedCore.getInstance(this).taskUpdateUserInfo(mListener, displayName, mobile, Email, areaID, gender, service.getAuthKey());
	}
	private void setErrorMsg(String msg, EditText viewId) {
		int ecolor = Color.RED; // whatever color you want
		String estring = msg;
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
		ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
		viewId.setError(ssbuilder);
	}
}
